<template>
  <div id="rule-log-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>规则日志管理</h2>
    </div>

    <!-- 日志列表展示区域 -->
    <div class="log-list-container">
      <el-card class="log-card">
        <template #header>
          <div class="card-header">
            <span>日志列表 ({{ props.logList.length }} 条)</span>
            <el-button 
              type="danger" 
              size="small" 
              @click="clearAllLogs"
              :disabled="props.logList.length === 0"
            >
              清空所有日志
            </el-button>
          </div>
        </template>

        <!-- 日志列表 -->
        <div class="log-list" v-if="props.logList.length > 0">
          <div 
            v-for="(log, index) in props.logList" 
            :key="index" 
            class="log-item"
            :class="{ 'log-item-even': index % 2 === 0 }"
          >
            <div class="log-time">
              <el-icon><Clock /></el-icon>
              {{ log.time }}
            </div>
            <div class="log-content">
              {{ log.content }}
            </div>
            <div class="log-actions">
              <el-button 
                type="danger" 
                size="small" 
                plain
                @click="deleteLog(index)"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else class="empty-state">
          <el-empty description="暂无日志数据">
            <el-button type="primary" @click="focusInput">添加第一条日志</el-button>
          </el-empty>
        </div>
      </el-card>
    </div>

    <!-- 添加日志输入区域 -->
    <div class="add-log-container">
      <el-card class="add-log-card">
        <template #header>
          <div class="card-header">
            <span>添加新日志</span>
          </div>
        </template>

        <el-form :model="newLog" label-width="80px">
          <el-form-item label="日志内容">
            <el-input
              ref="logInputRef"
              v-model="newLog.content"
              type="textarea"
              :rows="3"
              placeholder="请输入日志内容..."
              maxlength="500"
              show-word-limit
              @keydown.ctrl.enter="addLog"
            />
          </el-form-item>
          <el-form-item>
            <el-button 
              type="primary" 
              @click="addLog"
              :disabled="!newLog.content.trim()"
            >
              <el-icon><Plus /></el-icon>
              添加日志
            </el-button>
            <el-button @click="clearInput">
              <el-icon><Delete /></el-icon>
              清空输入
            </el-button>
            <span class="shortcut-tip">提示: Ctrl + Enter 快速添加</span>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { defineProps, defineEmits } from 'vue';

// 定义 props 从父组件接收数据
// 注意：v-model:log-list 对应的 prop 应该是 logList
const props = defineProps({
  logList: {
    type: Array,
    default: () => []
  }
});

// 监听 props 变化进行调试
watch(() => props.logList, (newVal) => {
  console.log('子组件 props.logList 变化:', newVal);
}, { immediate: true, deep: true });

// 定义 emits 向父组件发送事件
// v-model:log-list 对应 update:logList 事件
const emit = defineEmits(['update:logList']);

const newLog = ref({
  content: ''
});

const logInputRef = ref(null);

// 生成当前时间字符串
const getCurrentTimeString = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 添加日志
const addLog = () => {
  if (!newLog.value.content.trim()) {
    ElMessage.warning('请输入日志内容');
    return;
  }

  const log = {
    time: getCurrentTimeString(),
    content: newLog.value.content.trim()
  };

  console.log('当前 props.logList:', props.logList);
  console.log('新增的日志:', log);

  // 创建新的日志列表，添加新日志到顶部
  const newLogList = [log, ...props.logList];
  
  console.log('新的日志列表:', newLogList);
  
  // 通过 emit 向父组件发送更新后的日志列表
  emit('update:logList', newLogList);
  
  // 清空输入
  newLog.value.content = '';
  
  ElMessage.success('日志添加成功');
};

// 删除指定日志
const deleteLog = (index) => {
  ElMessageBox.confirm(
    '确定要删除这条日志吗？',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 创建新的日志列表，移除指定索引的日志
    const newLogList = [...props.logList];
    newLogList.splice(index, 1);
    
    // 通过 emit 向父组件发送更新后的日志列表
    emit('update:logList', newLogList);
    
    ElMessage.success('日志删除成功');
  }).catch(() => {
    // 取消删除
  });
};

// 清空所有日志
const clearAllLogs = () => {
  ElMessageBox.confirm(
    '确定要清空所有日志吗？此操作不可恢复！',
    '清空确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 通过 emit 向父组件发送空的日志列表
    emit('update:logList', []);
    
    ElMessage.success('所有日志已清空');
  }).catch(() => {
    // 取消清空
  });
};

// 清空输入框
const clearInput = () => {
  newLog.value.content = '';
};

// 聚焦到输入框
const focusInput = () => {
  nextTick(() => {
    if (logInputRef.value) {
      logInputRef.value.focus();
    }
  });
};
</script>

<style scoped>
#rule-log-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-weight: 600;
}

.log-list-container {
  margin-bottom: 20px;
}

.log-card, .add-log-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #303133;
}

.log-list {
  max-height: 600px;
  overflow-y: auto;
}

.log-item {
  display: flex;
  align-items: flex-start;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.3s;
}

.log-item:hover {
  background-color: #f8f9fa;
}

.log-item-even {
  background-color: #fafafa;
}

.log-item:last-child {
  border-bottom: none;
}

.log-time {
  display: flex;
  align-items: center;
  min-width: 160px;
  font-size: 14px;
  color: #909399;
  font-family: 'Courier New', monospace;
}

.log-time .el-icon {
  margin-right: 8px;
  color: #409eff;
}

.log-content {
  flex: 1;
  margin: 0 15px;
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
  word-break: break-word;
}

.log-actions {
  min-width: 80px;
  display: flex;
  justify-content: flex-end;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
}

.add-log-container {
  position: sticky;
  bottom: 20px;
  z-index: 100;
}

.shortcut-tip {
  font-size: 12px;
  color: #909399;
  margin-left: 10px;
}

/* 自定义滚动条 */
.log-list::-webkit-scrollbar {
  width: 6px;
}

.log-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.log-list::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
}

.log-list::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

/* 响应式设计 */
@media (max-width: 768px) {
  #rule-log-page {
    padding: 10px;
  }
  
  .log-item {
    flex-direction: column;
    gap: 10px;
  }
  
  .log-time {
    min-width: auto;
  }
  
  .log-content {
    margin: 0;
  }
  
  .log-actions {
    min-width: auto;
    justify-content: flex-start;
  }
}
</style>
